package com.kk.Utils;

import com.kk.work04.entity.Books;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class BookCsvUtil {
    public static List<Books> processCsvFile(MultipartFile file) {
        List<Books> bookList = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            // 跳过表头
            reader.readLine();
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 4) {
                    Books book = new Books();
                    book.setId(Integer.parseInt(parts[0].trim()));
                    book.setBookName(parts[1].trim());
                    book.setAuthor(parts[2].trim());
                    book.setPrice(Double.parseDouble(parts[3].trim()));
                    bookList.add(book);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bookList;
    }
}